<template>
  <div class="score">
    <template
      v-if="
        activeName === 4 &&
        retrainStatus?.retrain === 0 &&
        retrainStatus?.retrain_time
      "
    >
      <div class="not-start">
        <img src="@/assets/images/assignment/wrong-question-tip.png" />
        <p class="tip">
          重练尚未开始，将于{{
            dayjs(retrainStatus.retrain_time).format('YYYY-MM-DD HH:mm:ss')
          }}发放重练
        </p>
      </div>
    </template>
    <template v-else>
      <!-- 学生列表 -->
      <div class="student-box" v-if="getUnSubmitList.length">
        <div class="sign-box">
          <span class="left">未完成：{{ getUnSubmitList.length }}人</span>
          <p class="right">
            <!-- <span class="primary-text" @click="addTargetClass('un-submit')"
              ><img
                class="add-icon"
                src="@/assets/images/assignment/add-icon.png"
              />加入靶向班</span
            > -->
            <span class="primary-text" @click="isShowNameList = !isShowNameList"
              >{{ isShowNameList ? '收起' : '展开' }}名单</span
            >
          </p>
        </div>
        <template v-if="isShowNameList">
          <div class="student-list flex">
            <span
              v-for="(student, studentIndex) in getUnSubmitList"
              :key="studentIndex"
              class="student-item"
              :class="[
                taskInfo.taskType == 4 && 'hover',
                currentStudentId === student.studentId && 'student-item-active'
              ]"
            >
              {{ student.student_name }}
            </span>
          </div>
        </template>
      </div>
      <div class="search-box">
        <el-input
          class="class-name"
          placeholder="学生姓名"
          :suffix-icon="Search"
          v-model="search.studentName"
        ></el-input>
        <div class="right-rate">
          <p class="tip">任务正确率</p>
          <div class="input-box">
            <el-input-number
              placeholder="最低"
              :controls="false"
              :min="0"
              v-model="search.low_rate"
            ></el-input-number>
            <span class="separator">—</span>
            <el-input-number
              placeholder="最高"
              :controls="false"
              :max="100"
              v-model="search.high_rate"
            ></el-input-number>
          </div>
        </div>
        <el-select
          class="type"
          placeholder="全部题型"
          v-model="search.type"
          popper-class="question-type-popper"
        >
          <el-option
            v-for="item in questionType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        /></el-select>
        <span
          class="primary-text table-target"
          :class="{ 'disabled-text': selectionList.length === 0 }"
          @click="addTargetClass()"
        >
          <img
            v-if="selectionList.length === 0"
            class="add-icon"
            src="@/assets/images/assignment/add-disabled-icon.png"
          />
          <img
            v-else
            class="add-icon"
            src="@/assets/images/assignment/add-icon.png"
          />

          加入靶向班</span
        >
      </div>
      <el-table
        ref="tableRef"
        class="course-score-table"
        :data="getList"
        row-key="id"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" align="center" label="序号" width="100" />
        <el-table-column prop="studentName" align="center" label="姓名">
          <template #default="scope">
            <el-button type="text" @click="onRowClick(scope.row)" size="large">
              {{ scope.row.studentName }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="finish" align="center" label="完成情况">
          <template #default="scope">
            <div
              class="finish-row"
              :class="{ 'not-finish': scope.row.submit !== 1 }"
            >
              {{ scope.row.submit === 1 ? '已完成' : '未完成' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="isCorrect"
          align="center"
          label="批改状态"
          :sortable="true"
        >
          <template #default="scope">
            <span
              :style="{
                color:
                  scope.row.isCorrect === -1 && scope.row.submit === 1
                    ? '#3D54D9'
                    : '#333',
                cursor:
                  scope.row.isCorrect == -1 && scope.row.submit === 1
                    ? 'pointer'
                    : 'default'
              }"
              @click="toCorrect(scope.row)"
            >
              {{
                scope.row.submit === 1
                  ? scope.row.isCorrect === -1
                    ? '去批改'
                    : '已批改' || '-'
                  : '-'
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="scoreRate"
          align="center"
          label="正确率"
          :sortable="true"
        >
          <template #default="scope">
            <span :style="{ color: getRateColor(scope.row) }">
              {{
                (scope.row.score_rate === 0 || scope.row.score_rate) &&
                scope.row.isCorrect > -1 &&
                scope.row.submit === 1
                  ? parseFloat((scope.row.score_rate * 100).toFixed(1)) + '%'
                  : '-'
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="submit_time"
          align="center"
          label="提交时间"
          :sortable="true"
        >
          <template #default="scope">
            {{
              dayjs(scope.row.submit_time).valueOf() > 0
                ? dayjs(scope.row.submit_time).format('YYYY-MM-DD HH:mm:ss')
                : '-'
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="wrong-question"
          align="center"
          :label="activeName === 4 ? '本次重练错题' : '错题'"
        >
          <template #default="scope">
            <label
              class="wrong-label"
              v-for="item in (scope.row.wrong_question || []).sort(
                (item1, item2) => item1.index - item2.index
              )"
              :key="item"
              >{{ item.index + 1 }}</label
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="teacher_name"
          align="center"
          label="批改人"
        ></el-table-column>
      </el-table>
    </template>
    <CreateTargetClass
      :visible="targetVisible"
      @close="closeTargetDialog"
      :currentGrade="classSelect.grade_id"
      :studentList="targetClassStudents"
      :teacherId="authStore.userInfo.userId"
      :schoolId="authStore.userInfo.school_id"
    ></CreateTargetClass>
  </div>
</template>

<script setup>
import router from '@/router'
import { debounce } from '@/utils/debounce.js'
import { Search } from '@element-plus/icons-vue'
import { ref, watch, computed } from 'vue'
import { getScoreDetail, getWrongDetail } from '@/apis/assignment/index'
import dayjs from 'dayjs'
import CreateTargetClass from '@/views/class-manage/cpns/CreateTargetClass.vue'
import { useAuthStore } from '@/stores/auth-store.js'
import { ElMessage } from 'element-plus'
import { CORRECT_TYPE } from '../single-correct/data'
const authStore = useAuthStore()

const props = defineProps({
  taskInfo: {
    type: Object,
    required: true
  },
  taskId: {
    required: true
  },
  classSelect: {
    required: true
  },
  activeName: {
    required: true
  },
  retrainStatus: {
    type: Object
  }
})

// 学生列表
/* eslint-enable */
const studentLayerList = ref([
  {
    bg1: '#F7F9FF',
    bg2: 'rgba(84, 102, 231, 0.1)',
    color: '#5466E7',
    text: '未完成',
    list: []
  }
])

const unSubmitStudents = ref([])

const getRateColor = row => {
  const rate = row.score_rate * 100
  if (row.isCorrect > -1 && row.submit === 1) {
    if (rate !== 0 && !rate) {
      return '#333'
    } else if (rate >= 80) {
      return '#25A780'
    } else if (rate >= 60) {
      return '#ACDB4A'
    } else {
      return '#DC4834'
    }
  } else {
    return '#333'
  }
}

const questionType = [
  {
    label: '全部题型',
    value: ''
  },
  {
    label: '主观题',
    value: '1'
  },
  {
    label: '客观题',
    value: '2'
  }
]

const isShowNameList = ref(false)

const search = ref({
  studentName: '',
  low_rate: undefined,
  high_rate: undefined,
  type: ''
})
const studentList = ref([])

// 课程任务成绩列表
const getCourseGradeInfo = async () => {
  const res = await getScoreDetail({
    task_id: props.taskId,
    class_id: props.classSelect.value,
    class_type: props.classSelect.class_type,
    student_name: search.value.studentName,
    question_type: search.value.type,
    low_rate: search.value.low_rate ? search.value.low_rate : 0,
    high_rate: search.value.high_rate ? search.value.high_rate : 100
  })
  unSubmitStudents.value = res.data?.un_submit_list?.list || []
  studentList.value = (res.data?.student_info?.list || []).map(
    (student, index) => ({
      id: index,
      studentName: student.student_name,
      finish: student.status,
      scoreRate: student.score_rate,
      isCorrect: student.teacher_correct,
      ...student
    })
  )
}

//  错题重练列表
const wrongStudentList = ref([])
const wrongUnSubmitList = ref([])
const getWrongInfo = async () => {
  const res = await getWrongDetail({
    task_id: props.taskId,
    class_id: props.classSelect.value,
    class_type: props.classSelect.class_type,
    student_name: search.value.studentName,
    question_type: search.value.type,
    low_rate: search.value.low_rate ? search.value.low_rate : 0,
    high_rate: search.value.high_rate ? search.value.high_rate : 100
  })
  wrongUnSubmitList.value = res.data?.un_submit_list?.list || []
  wrongStudentList.value = (res.data?.student_info?.list || []).map(
    (student, index) => ({
      id: index,
      studentName: student.student_name,
      finish: student.status,
      scoreRate:
        student.score_rate === 0
          ? '-'
          : (student.score_rate * 100).toFixed(0) + '%',
      isCorrect: student.teacher_correct,
      ...student
    })
  )
}

const getUnSubmitList = computed(() => {
  const res =
    props.activeName === 4 ? wrongUnSubmitList.value : unSubmitStudents.value
  return res
})
const getList = computed(() => {
  const res =
    props.activeName === 4 ? wrongStudentList.value : studentList.value
  return res
})
const onRowClick = row => {
  if (!row.submit) return
  router.push({
    name: 'oneThreeDetail',
    query: {
      task_id: props.taskId,
      taskInfo: JSON.stringify(row)
    }
  })
}
const targetClassStudents = ref([])
const targetVisible = ref(false)
const addTargetClass = from => {
  targetClassStudents.value = []
  if (from === 'un-submit') {
    tableRef.value?.clearSelection()
    targetClassStudents.value = getUnSubmitList.value.map(item => {
      return {
        studentName: item.student_name,
        key: item.student_id,
        ...item
      }
    })
  } else {
    if (!selectionList.value.length) {
      ElMessage.warning('请先选择学生！')
      return
    }
    targetClassStudents.value = selectionList.value
  }
  targetVisible.value = true
}

const closeTargetDialog = val => {
  targetVisible.value = false
  if (val === 'refresh') tableRef.value && tableRef.value.clearSelection()
}

const tableRef = ref()
const selectionList = ref([])
const handleSelectionChange = val => {
  selectionList.value = (val || []).map(student => {
    return {
      studentName: student.student_name,
      key: student.student_id
    }
  })
}

const toCorrect = task => {
  if (task.isCorrect == -1 && task.submit === 1) {
    if (props.taskInfo.correct_type === CORRECT_TYPE.ROUGH) {
      router.push({
        name: 'detailCorrect',
        query: {
          taskId: props.taskId,
          name: props.taskInfo.name,
          classList: JSON.stringify(
            (props.taskInfo.classList || []).map(item => ({
              classId: item.value,
              className: item.label,
              classType: item.class_type
            }))
          )
        }
      })
    } else {
      router.push({
        name: 'singleCorrect',
        query: {
          taskId: props.taskInfo.task_id
        }
      })
    }
  }
}

const getData = () => {
  if (props.activeName === 1) {
    getCourseGradeInfo()
  } else if (props.activeName === 4 && props.retrainStatus?.retrain === 1) {
    getWrongInfo()
  }
}

watch(
  () => search.value,
  () => {
    debounce(() => {
      getData()
    }, 500)
  },
  {
    deep: true
  }
)

watch(
  [() => props.classSelect, () => props.activeName],
  () => {
    getData()
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<style lang="less" scoped>
.score {
  display: flex;
  flex-direction: column;
  background: #fff;
  padding: 24px;

  .student-box {
    height: fit-content;
    flex-shrink: 0;
    margin-bottom: 20px;
    background-color: #fdf8f1;

    .sign-box {
      height: 36px;
      text-align: center;
      color: #ffae10;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-right: 16px;

      .left {
        line-height: 36px;
        height: 36px;
        background: #ffae101a;
        padding: 0 15px;
        font-size: 14px;
      }
    }

    .student-list {
      padding: 20px;
      flex-wrap: wrap;
      gap: 10px;

      .student-item {
        color: #333;
        padding: 0 4px;
      }
    }

    :deep(.el-empty) {
      padding: 0 !important;
    }
  }

  .primary-text {
    cursor: pointer;
    margin-left: 30px;
    color: #5466e7;
    font-size: 16px;
    display: inline-flex;
    align-items: center;

    .add-icon {
      width: 14px;
      margin-right: 8px;
    }
  }

  .table-target {
    margin-left: auto;
    margin-right: 8px;

    &.disabled-text {
      cursor: not-allowed;
      color: #72757e !important;
    }
  }

  .search-box {
    height: fit-content;
    flex-shrink: 0;
    display: flex;
    gap: 40px;
    margin-bottom: 20px;

    :deep(.class-name) {
      width: 220px;
      height: 30px !important;

      .el-input__wrapper {
        border-radius: 0;
        box-shadow: none;
        border: 1px solid #b7b8bb;

        .el-input__inner {
          font-size: 14px;

          &::placeholder {
            font-size: 14px;
          }
        }
      }
    }
    .right-rate {
      display: flex;
      align-items: center;
      border: 1px solid #b7b8bb;
      height: 30px;

      * {
        font-size: 14px;
      }

      .tip {
        padding: 0 10px;
        font-size: 14px;
        color: #333333;
        width: fit-content;
        white-space: nowrap;
        border-right: 1px solid #b7b8bb;
        height: 100%;
        line-height: 30px;
      }

      .separator {
        color: #b7b8bb;
      }

      .input-box {
        .el-input-number {
          width: 100px;
          height: 28px;

          :deep(.el-input__wrapper) {
            border-radius: 0;
            // border: 1px solid #b7b8bb;
            border-left: unset;
            border-right: unset;
            box-shadow: none;
          }
        }
      }
    }

    .type {
      width: 108px;

      :deep(.el-select__wrapper) {
        border-radius: 0;
        box-shadow: none;
        border: 1px solid #b7b8bb;
      }
    }
  }

  .course-score-table {
    flex: 1;
    overflow-y: scroll;

    .finish-row {
      gap: 10px;
    }

    .not-finish {
      color: #b7b8bb;
    }

    .wrong-label {
      display: inline-block;
      color: #ea4338;
      border: 1px solid #ea4338;
      padding: 0 8px;
      height: 24px;
      line-height: 24px;
      margin-right: 4px;
    }

    /* stylelint-disable ebag/selector-class-pattern */
    :deep(.cell) {
      line-height: 40px !important;

      .el-table__expand-icon {
        display: none;
      }
    }

    :deep(.caret-wrapper) {
      height: 12px;
    }

    :deep(.el-table__header) {
      .el-table__cell {
        background-color: #f2f4f9;
      }
    }
  }

  .not-start {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 600px;
    justify-content: center;

    img {
      width: 254px;
    }

    .tip {
      color: #333;
      font-size: 14px;
      margin-top: 20px;
    }
  }
}
</style>
<!-- eslint-disable -->
<style lang="less">
.question-type-popper {
  .el-select-dropdown__item {
    font-size: 14px;
  }
}
</style>
